package com.tskj.leonsu.controller;

import com.alibaba.fastjson.JSONObject;
import com.tskj.leonsu.service.LoginService;
import com.tskj.leonsu.service.SystemService;
import com.tskj.leonsu.utility.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class SystemController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private SystemService systemService;

    @PostMapping("/login")
    @ResponseBody
    public JSONObject login(@RequestBody JSONObject userInfo) {
        JSONObject result;
        if (!userInfo.containsKey("userName") ||
            userInfo.getString("userName") == null ||
            userInfo.getString("userName").isEmpty()) {
            result = new JSONObject();
            result.put("code", 1);
            result.put("errMsg", "用户名不能为空");
            return result;
        }
        if (!userInfo.containsKey("password") ||
                userInfo.getString("password") == null ||
                userInfo.getString("password").isEmpty()) {
            result = new JSONObject();
            result.put("code", 1);
            result.put("errMsg", "密码不能为空");
            return  result;
        }
        result = loginService.login(userInfo.getString("userName"), userInfo.getString("password"), userInfo.getBoolean("nologin"));
        if (result.getInteger("code") != 0) {
            return result;
        }
        return result;
    }

    @PostMapping("/check")
    @ResponseBody
    public JSONObject checkLongToken(@RequestBody JSONObject data) {
        JSONObject ret = new JSONObject();
        if (!data.containsKey("code") || data.get("code") == null || data.getString("code").isEmpty()) {
            ret.put("code", 1);
            ret.put("errMsg", "无效的登录码");
            return ret;
        }
        String code = data.getString("code");
        return loginService.checkLongToken(code);
    }

    @GetMapping("/module")
    @ResponseBody
    public JSONObject getModuleList() {
        JSONObject ret = new JSONObject();
        ret.put("code", 0);
        ret.put("data", systemService.getModuleList());
        return ret;
    }
}
